<?php
declare(strict_types = 1);
namespace Haozing\FastCore\Utils\Response;

use Hyperf\HttpMessage\Stream\SwooleStream;
use Haozing\FastCore\Log\RequestIdHolder;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Swow\Psr7\Message\ResponsePlusInterface;

class Response extends \Hyperf\HttpServer\Response
{
    /**
     * @param string|null $message
     * @param array|object $data
     * @param int $code
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function success(string $message = null, array|object $data = [], int $code = 200): ResponseInterface
    {
        $format = [
            'requestId' => RequestIdHolder::getId(),
            'success' => true,
            'message' => $message ?: t('fastCore.response_success'),
            'code'    => $code,
            'data'    => &$data,
        ];
        $format = $this->toJson($format);
        return $this->getResponse()
            ->withHeader('Server', 'fastCore')
            ->withAddedHeader('content-type', 'application/json; charset=utf-8')
            ->withBody(new SwooleStream($format));
    }

    /**
     * @param string $message
     * @param int $code
     * @param array $data
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function error(string $message = '', int $code = 500, array $data = []): ResponseInterface
    {
        $format = [
            'requestId' => RequestIdHolder::getId(),
            'success' => false,
            'code'    => $code,
            'message' => $message ?: t('fastCore.response_error'),
        ];

        if (!empty($data)) {
            $format['data'] = &$data;
        }

        $format = $this->toJson($format);
        return $this->getResponse()
            ->withHeader('Server', 'fastCore')
            ->withAddedHeader('content-type', 'application/json; charset=utf-8')
            ->withBody(new SwooleStream($format));
    }

    /**
     * 向浏览器输出图片
     * @param string $image
     * @param string $type
     * @return ResponseInterface
     */
    public function responseImage(string $image, string $type = 'image/png'): ResponseInterface
    {
        return $this->getResponse()->withHeader('Server', 'fastCore')
            ->withAddedHeader('content-type', $type)
            ->withBody(new SwooleStream($image));
    }

    /**
     * @return ResponsePlusInterface
     */
    public function getResponse(): ResponsePlusInterface
    {
        return parent::getResponse(); // TODO: Change the autogenerated stub
    }
}